package com.zygame.sdk;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Application;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.RemoteException;
import android.support.annotation.NonNull;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;

import com.facebook.appevents.AppEventsLogger;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Scope;
import com.zygame.sdk.bean.ConfigMessage;
import com.zygame.sdk.bean.GameServerParams;
import com.zygame.sdk.bean.PayResult;
import com.zygame.sdk.bean.SDKParams;
import com.zygame.sdk.bean.UserBean;
import com.zygame.sdk.bean.ZY_PayParams;
import com.zygame.sdk.bean.ZY_Toolbar;
import com.zygame.sdk.db.UserDao;
import com.zygame.sdk.interfaces.CmSDKListener;
import com.zygame.sdk.interfaces.IActivityCallback;
import com.zygame.sdk.interfaces.IApplicationListener;
import com.zygame.sdk.interfaces.ICmGameSDK;
import com.zygame.sdk.interfaces.InitResult;
import com.zygame.sdk.interfaces.ZySDKListener;
import com.zygame.sdk.model.UserModel;
import com.zygame.sdk.service.HeartbeatService;
import com.zygame.sdk.utils.MD5Util;
import com.zygame.sdk.utils.ProgressDialogUtil;
import com.zygame.sdk.utils.SDKTools;
import com.zygame.sdk.utils.SharedPreferencesHelper;
import com.zygame.sdk.utils.http.HttpUtil;
import com.zygame.sdk.utils.http.NetHttpUtil;
import com.zygame.sdk.utils.http.NetHttpUtil.DataCallback;
import com.zygame.sdk.utils.http.NetWorkUtil;
import com.zygame.sdk.utils.log.LogHelper;
import com.zygame.sdk.utils.toast.ToastUtil;
import com.zygame.sdk.utils.util.IabHelper;
import com.zygame.sdk.utils.util.IabResult;
import com.zygame.sdk.utils.util.Inventory;
import com.zygame.sdk.utils.util.Purchase;
import com.zygame.sdk.view.dialog.ZY_Dialog_AccountCenter;
import com.zygame.sdk.view.dialog.Zy_Dialog_PayWay;
import com.zygame.sdk.view.dialog.Zy_Dialog_main;
import com.zygame.sdk.view.floatbutton.FloatToolBar;
import com.zygame.sdk.view.floatbutton.FloatWindow;
import com.zygame.sdk.view.web.ZY_Act_WebView;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Currency;
import java.util.List;
import java.util.Locale;

public class ZyGameSDK implements ICmGameSDK {

    private static final String DEFAULT_PKG_NAME = "com._65.sdk";
    private static final String TAG = "_cmSDK";
    public static final int RC_SIGN_IN = 10001;
    private static ZyGameSDK instance;

    public static int dialogDismissFlag = 0; // 对话框消失标记
    public static boolean onSwitchAccountFlag = false; // 切换账号

    private Application application;
    private Activity mContext;
    private Handler mainThreadHandler;

    private SDKParams developInfo;
    private Bundle metaData;

    private List<CmSDKListener> listeners;
    private ZySDKListener listener;
    private boolean isInit = false;

    private List<IActivityCallback> activityCallbacks;

    // private List<IApplicationListener> applicationListeners;

    private String sdkUserID = null;
    private String mServerId;
    private boolean menuFlag = false;
    private boolean versionFlag = false;

    private static boolean isDebug;

    // 热云sdk
    public static boolean reyunFlag = false;

    // talkingdata
    public static boolean talkingdataFlag = false;
    private String token;
    private InitResult initResult;
    private ProgressDialog progressDialog;
    private SharedPreferencesHelper spHelper;
    private Intent serviceIntent;
    private IabHelper mIabHelper;

    private ZyGameSDK() {
        mainThreadHandler = new Handler(Looper.getMainLooper());
        listeners = new ArrayList<CmSDKListener>();
        activityCallbacks = new ArrayList<IActivityCallback>(1);
        // applicationListeners = new ArrayList<IApplicationListener>(2);
        LogHelper.i("CmGameSDK", "构造方法");
    }

    public void setDebug(boolean isDebug) {
        isDebug = isDebug;
        LogHelper.setLOGDBUG(isDebug);
    }

    public boolean isDebug() {
        return this.isDebug;
    }

    public static ZyGameSDK getInstance() {
        if (instance == null) {
            instance = new ZyGameSDK();
        }
        return instance;
    }

    public SDKParams getSDKParams() {
        return developInfo;
    }

    public Bundle getMetaData() {
        return metaData;
    }

    public boolean getReyunFlag() {
        if (this.developInfo == null || !this.developInfo.contains("REYUN_FLAG")) {
            return true;
        }

        return this.developInfo.getBoolean("REYUN_FLAG");
    }

    public boolean getTalkingDataFlag() {

        if (this.developInfo == null || !this.developInfo.contains("TALKINGDATA_FLAG")) {
            return true;
        }

        return this.developInfo.getBoolean("TALKINGDATA_FLAG");
    }

    /**
     * 获取当前SDK对应的渠道号
     *
     * @return
     */
    //	public String getChannelID() {
    //
    //		if (this.developInfo == null || !this.developInfo.contains("CHANNEL_ID")) {
    //			return "0";
    //		} else {
    //			return this.developInfo.getString("CHANNEL_ID");
    //		}
    //	}

    /*
     * 获取版本
     */
    public String getSDKVersion() {

        if (this.developInfo == null || !this.developInfo.contains("SDK_VERSION")) {
            return "0";
        } else {
            return this.developInfo.getString("SDK_VERSION");
        }
    }

    public String getGameID() {
        if (this.developInfo == null || !this.developInfo.contains("GAME_ID")) {
            return 0 + "";
        }

        return this.developInfo.getString("GAME_ID");
    }


//    public void splashInit(Activity context, ZySDKListener listeners) {
//        if (listeners == null) {
//            ToastUtil.showToast(context, "I65SDKListener参数不能为null");
//            return;
//        }
//        this.listener = listeners;
//
//        this.mContext = context;
//
//        Log.i("eeeeee", context.toString());
//        //        initSdk();
//        parseSDKParams(context);//初始化assets文件
//        checkNetwork(context);//网络请求
//        context.setRequestedOrientation(getOrientation() ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//设置横屏
//    }

    public String getGameKey() {
        if (this.developInfo == null || !this.developInfo.contains("ZY_GAMEID")) {
            return "";
        }

        return this.developInfo.getString("ZY_GAMEID");
    }

    public String getPrivateKey() {
        if (this.developInfo == null || !this.developInfo.contains("ZY_KEY")) {
            return "";
        }

        return this.developInfo.getString("ZY_KEY");
    }

    /**
     * 获取屏幕方向
     * <p>
     * true : 横屏 false ： 竖屏 ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE 横屏
     * ActivityInfo.SCREEN_ORIENTATION_PORTRAIT 竖屏
     */
    public boolean getOrientation() {
        if (this.developInfo == null || !this.developInfo.contains("ORIENTATION")) {
            return true;
        }

        return this.developInfo.getBoolean("ORIENTATION");
    }

    public void setSDKListener(CmSDKListener listener) {
        if (!listeners.contains(listener) && listener != null) {
            this.listeners.add(listener);
        }
    }

    public void setActivityCallback(IActivityCallback callback) {
        // this.activityCallback = callback;
        if (!this.activityCallbacks.contains(callback) && callback != null) {
            this.activityCallbacks.add(callback);
        }

    }


    public Application getApplication() {

        return this.application;
    }

    public String getSDKUserID() {
        return this.sdkUserID;
    }

    /**
     * 设置对话框消失标记
     *
     * @param flag
     */
    public void setDialogDismissFlag(int flag) {
        dialogDismissFlag = flag;
    }

    public void setOnSwitchAccountFlag(boolean flag) {
        onSwitchAccountFlag = flag;
    }

    /**
     * 开启心跳包
     *
     * @param sid 游戏服id
     * @param uid
     */
    public void startHeartServer(Activity activity, String sid, String uid) {
        if (isWorked())
            return;
        String cid = "";
        String gid = ""; // 游戏id
        serviceIntent = new Intent(activity, HeartbeatService.class);
        //        String heartUrl = "http://" + gid + ".tj.650063.com/" + sid + ".html?uid=" + uid + "&cid=" + cid;
        //        if (uid != null) {
        //        serviceIntent.putExtra("url", heartUrl);
        activity.startService(serviceIntent);
        //        }
    }

    /**
     * 判断心跳包是否运行
     * <p>
     * 本方法判断自己些的一个Service-->是否已经运行
     *
     * @return
     */
    public static boolean isWorked() {
        ActivityManager myManager = (ActivityManager) ZyGameSDK.getInstance().getContext().getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<RunningServiceInfo> runningService = (ArrayList<RunningServiceInfo>) myManager.getRunningServices(30);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().toString().equals("com.zygame.sdk.service.HeartbeatService")) {
                return true;
            }
        }
        return false;
    }

    /**
     * 初始化解析参数
     *
     * @param context
     */
    public void parseSDKParams(Context context) {

        //		reyunFlag = getReyunFlag();
        //		talkingdataFlag = getTalkingDataFlag();


        developInfo = PluginFactory.getInstance().getSDKParams(context);
        ConstantValue.ZY_CID = developInfo.getString("ZY_CID");
        ConstantValue.ZY_GAMEID = developInfo.getString("ZY_GAMEID");
        ConstantValue.ZY_KEY = developInfo.getString("ZY_KEY");
        ConstantValue.VERSIONCODE = developInfo.getString("ZY_VERSIONCODE");
        ConstantValue.VERSIONAME = developInfo.getString("ZY_VERSION_NAME");
        ConstantValue.ZY_LANGUAGE = developInfo.getString("ZY_LANGUAGE");
        ConstantValue.APP_ID = developInfo.getString("ZY_WECHATID");
        ConstantValue.APP_key = developInfo.getString("ZY_WECHATKEY");
        ConstantValue.ZY_SERVER_AUTHCODE = developInfo.getString("ZY_SERVER_AUTHCODE");
        ConstantValue.ZY_BASE64KEY = developInfo.getString("ZY_BASE64KEY");


        spHelper = SharedPreferencesHelper.getInstance();
        spHelper.setLogin_Token(mContext, "");
        spHelper.setToken(mContext, "");
        spHelper.setGameJson(mContext, "");
        spHelper.setPayUrl(mContext, "");
        spHelper.setGMail(mContext, "");
        spHelper.setWechat(mContext, "");


    }

    @SuppressWarnings("rawtypes")
    private IApplicationListener newApplicationInstance(Application application, String proxyAppName) {

        if (proxyAppName == null || SDKTools.isNullOrEmpty(proxyAppName)) {
            return null;
        }

        if (proxyAppName.startsWith(".")) {
            proxyAppName = DEFAULT_PKG_NAME + proxyAppName;
        }

        try {
            Class clazz = Class.forName(proxyAppName);
            return (IApplicationListener) clazz.newInstance();

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return null;
    }

    public void runOnMainThread(Runnable runnable) {
        if (mainThreadHandler != null) {
            mainThreadHandler.post(runnable);
            return;
        }

        if (mContext != null) {
            mContext.runOnUiThread(runnable);
        }
    }

    public Activity getContext() {
        return this.mContext;
    }


    public void onInitResult(InitResult result) {
        listener.onInitResult(result);
        isInit = true;
        //        }
    }

    public void onLoginResult(UserModel userModel) {

        //        for (CmSDKListener listener : listeners) {
        listener.onLoginResult(userModel);
        //        }
    }


    public void onLogout() {
        //        for (CmSDKListener listener : listeners) {
        listener.onLogout();
        //        }
    }

    public void onPayResult(PayResult result) {
        //        for (CmSDKListener listener : listeners) {
        listener.onPayResult(result);
        //        }
    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (this.activityCallbacks != null) {
            for (IActivityCallback callback : this.activityCallbacks) {
                callback.onActivityResult(requestCode, resultCode, data);
            }

        }
    }

    public void onBackPressed() {
        if (this.activityCallbacks != null) {
            for (IActivityCallback callback : this.activityCallbacks) {
                callback.onBackPressed();
            }

        }
    }

    public void onCreate() {
        if (this.activityCallbacks != null) {
            for (IActivityCallback callback : this.activityCallbacks) {
                callback.onCreate();
            }

        }
    }

    public void onStart() {
        if (this.activityCallbacks != null) {
            for (IActivityCallback callback : this.activityCallbacks) {
                callback.onStart();
            }
        }
    }

    public void onPause() {
        if (this.activityCallbacks != null) {
            for (IActivityCallback callback : this.activityCallbacks) {
                callback.onPause();
            }

        }
    }

    public void onResume() {

        if (this.activityCallbacks != null) {
            for (IActivityCallback callback : this.activityCallbacks) {
                callback.onResume();
            }

        }

    }

    public void onNewIntent(Intent newIntent) {
        if (this.activityCallbacks != null) {
            for (IActivityCallback callback : this.activityCallbacks) {
                callback.onNewIntent(newIntent);
            }

        }

    }

    public void onStop() {
        if (this.activityCallbacks != null) {
            for (IActivityCallback callback : this.activityCallbacks) {
                callback.onStop();
            }

        }

    }

    public void onDestroy() {
        if (this.activityCallbacks != null) {
            for (IActivityCallback callback : this.activityCallbacks) {
                callback.onDestroy();
            }

        }

    }

    public void onRestart() {
        if (this.activityCallbacks != null) {
            for (IActivityCallback callback : this.activityCallbacks) {
                callback.onRestart();
            }

        }

    }

    /**
     * 激活接口, 在用户登录前使用，收集运行了游戏的手机信息
     */
    private void active() {
        HttpUtil.active(getContext(), onActiveCallBack);
    }

    DataCallback<JSONObject> onActiveCallBack = new DataCallback<JSONObject>() {

        @Override
        public void callbackSuccess(JSONObject paramObject) {
            String code = paramObject.optString("code").trim();
            String msg = paramObject.optString("msg").trim();
            LogHelper.i("active接口返回：", paramObject.toString());
            if ("0".equals(code)) {
                //                getSharedPreferences("tokeninfo", 0).edit().putString("token", paramObject.optString("token")).commit();
                token = paramObject.optString("token");
                SharedPreferencesHelper.getInstance().setToken(mContext, token);
                //获取SDK基础配置

                getMenu(token);

            } else {
                LogHelper.i("active接口返回：", "激活失败,--->" + msg);
                active();
            }
        }

        @Override
        public void callbackError(String error) {
            active();
            LogHelper.i("activi接口返回：", "失败");
        }

    };


    private void getMenu(String token) {
        HttpUtil.get_menu(mContext, onMenuCallBack, token);
    }

    DataCallback<JSONObject> onMenuCallBack = new DataCallback<JSONObject>() {

        @Override
        public void callbackSuccess(JSONObject paramObject) {
            String code = paramObject.optString("code").trim();
            String msg = paramObject.optString("msg").trim();
            LogHelper.i("get_menu接口返回：", paramObject.toString());
            if ("0".equals(code)) {
                menuFlag = true;
                //                spHelper.setToolBar();
                ConfigMessage.getInstance().jsonParse(paramObject, mContext);
                if (menuFlag && versionFlag) {
                    progressDialog.dismiss();
                    onInitResult(initResult);

                    //splashListener.splashInit();
                }
            } else {
                getMenu(token);
            }
        }

        @Override
        public void callbackError(String error) {
            getMenu(token);
            LogHelper.i("get_menu接口返回：", "失败");
        }
    };


    /**
     * @param context
     */
    public void init(Activity context, ZySDKListener listeners) {
        menuFlag = false;
        versionFlag = false;
        UserModel.getInstance().clearUser();
        if (listeners == null) {
            ToastUtil.showToast(context, "ZySDKListener参数不能为null");
            return;
        }


        this.mContext = context;
        //Intent intent = new Intent(context, ZY_HeartbeatService.class);
        //context.startService(intent);
        this.listener = listeners;
        if (!isInit) {
            parseSDKParams(context);//初始化assets文件
            checkNetwork(context);//网络请求

        } else {
            listeners.onInitResult(initResult);
        }
        context.setRequestedOrientation(getOrientation() ? ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE : ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//设置横屏
        startHeartServer(mContext, "", "");
        LogHelper.i("CmGameSDK", "iniyt");
    }

    private void initLanguage() {
        Resources resources = mContext.getResources();
        DisplayMetrics dm = resources.getDisplayMetrics();
        Configuration config = resources.getConfiguration();
        try {
            if (ConstantValue.ZY_LANGUAGE.equals("1000")) {
                // 应用用户选择语言
                config.locale = Locale.ENGLISH;
            } else {
                config.locale = Locale.CHINESE;
            }

            resources.updateConfiguration(config, dm);


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }


    /**
     * @Title: checkNetwork(无网络时提示, 有网络获取配置文件)
     * @author
     * @data
     */
    public void checkNetwork(Activity context) {
        if (NetWorkUtil.isNetworkAvailable(context)) {//判断网络是否可用
            progressDialog = new ProgressDialog(context);
            progressDialog.setCancelable(false);
            progressDialog.show();
            active(); // 激活
            requestInitConfig(context); // 请求数据
        } else {
            ProgressDialogUtil.showInfoDialog(context, "提示", "当前网络不稳定,请检查您的网络设置！", 0, new OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // repeatInit();
                    if (!NetWorkUtil.isNetworkAvailable(getContext())) {
                        Intent intent = null;
                        /*
                         * 判断手机系统的版本 即API大于10 就是3.0或以上版本 程序启动时检测是否有网络，无网络时打开设置界面
                         */
                        if (android.os.Build.VERSION.SDK_INT > 10) {
                            intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                        } else {
                            intent = new Intent();
                            ComponentName component = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
                            intent.setComponent(component);
                            intent.setAction("android.intent.action.VIEW");
                        }
                        getContext().startActivityForResult(intent, 0);
                    }
                }
            }, "确定", null, null, false);
        }
    }

    /**
     * 获取配置文件
     *
     * @Title: requestInit(SDK初始化请求)
     * @author
     * @data
     */
    private synchronized void requestInitConfig(Context context) {
        //HttpUtil.requestInitConfig(context, onConfigCallBack);
        HttpUtil.game_version(context, onGameCallBack);

        //HttpUtil.getVersion(context, getVersionCallback);
    }


    private DataCallback<JSONObject> onGameCallBack = new DataCallback<JSONObject>() {

        @Override
        public void callbackSuccess(JSONObject paramObject) {
            LogHelper.i("game接口返回：", paramObject.toString());
            Log.i("game接口返回：", paramObject.toString());
            String code = paramObject.optString("code").trim();
            if ("0".equals(code)) {
                versionFlag = true;
                try {
                    JSONObject version = new JSONObject(paramObject.optString("version"));
                    initResult = new InitResult();
                    initResult.setUpData(true);
                    initResult.setUplaod(version.getString("download_url"));
                    initResult.setPay_way(version.getInt("pay_way"));
                    SharedPreferencesHelper.getInstance().setPayUrl(mContext, version.getString("is_purl"));
                    if (menuFlag && versionFlag) {
                        progressDialog.dismiss();
                        onInitResult(initResult);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                requestInitConfig(mContext);
            }
        }

        @Override
        public void callbackError(String error) {
            LogHelper.i("sss", error + " game失败");
            requestInitConfig(mContext);
        }

    };


    @Override
    public void login() {
        // 自动设置账号密码
        UserDao ud = new UserDao();
        UserBean ub = ud.query(ud._LAST_LOGIN_FLAG, "1", "");

        if (ub != null) {
            new ZY_Dialog_AccountCenter(mContext).show();//数据库有用户记录 直接去自动登录
        } else {
            if(mContext == null || mContext.isFinishing() || mContext.isDestroyed()){
                return;
            }

            try {
                Zy_Dialog_main login = Zy_Dialog_main.getInstance(mContext);
                login.show();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void logout() {
        // 热云退出
        if (reyunFlag) {
            //ReYunTrack.exitSdk();
        }
        if (UserModel.getInstance().getLogin_Token() != null) {
            HttpUtil.logout(mContext, outCallBack);
            //HttpUtil.exitAccount(mContext, UserModel.getInstance().getToken());
            UserModel.getInstance().clearUser();
            SharedPreferencesHelper.getInstance().setGameJson(mContext, "");
            //ZyGameSDK.getInstance().onResult(CmCode.CODE_LOGOUT_SUCCESS, "65sdk logout");
            ZyGameSDK.getInstance().onLogout();
        }
    }


    @Override
    public void restart() {

    }

    @Override
    public void showFloatButton(Activity activity, boolean showlasttime, int align, float position) {
        //if (SharedPreferencesHelper.getInstance().getToolBar(mContext).equals("1")) {    // 0开启， 1关闭
        if (null != UserModel.getInstance().getLogin_Token()) {

            if(mContext == null || mContext.isFinishing() || mContext.isDestroyed()){
                return;
            }
            FloatToolBar toolBar = FloatToolBar.getFloatToolBar(activity, showlasttime, FloatToolBar.FloatToolBarAlign.Left, position);
            toolBar.show();
            //            }

            //if (FloatWindow.getInstance() != null) {
            //    FloatWindow.getInstance().hideMenu();
            //}
        }
    }

    @Override
    public void hideFloatButton() {
        if (FloatToolBar.getInstance() == null) {
            return;
        }
        if (FloatWindow.getInstance().isShowing()) {
            FloatToolBar.getInstance().hide();
        }
    }

    @Override
    public void recycleFloatButton() {
        if (FloatToolBar.getInstance() == null) {
            return;
        }
        if (FloatWindow.getInstance().isShowing()) {
            FloatToolBar.getInstance().hide();
            FloatToolBar.getInstance().recycle();
        }
    }


    public void googleSignIn() {
//        mContext.startActivity(new Intent(mContext, Zy_GooglePay.class));
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestScopes(new Scope(Scopes.DRIVE_APPFOLDER))
                .requestEmail()
                .requestServerAuthCode(ConstantValue.ZY_SERVER_AUTHCODE)
                .build();

        /* FragmentActivity *//* OnConnectionFailedListener */
        GoogleApiClient mGoogleApiClient = new GoogleApiClient.Builder(mContext)
                .enableAutoManage((FragmentActivity) mContext /* FragmentActivity */, mOnConnectionFailedListener /* OnConnectionFailedListener */)
                .addApi(Auth.GOOGLE_SIGN_IN_API, gso)
                .build();

        Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mGoogleApiClient);
        mContext.startActivityForResult(signInIntent, RC_SIGN_IN);
    }



    private GoogleApiClient.OnConnectionFailedListener mOnConnectionFailedListener = new GoogleApiClient.OnConnectionFailedListener() {
        @Override
        public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

        }
    };



    /**
     * 游戏内充值 activity: currency:货币类型 serviceName: 游戏服名称 currencyMes: 商品信息 String
     * other:自定义数据，充值成功回调时候原样返回
     */
    private static long lastClickTime;
    private int payWay;

    @Override
    public void pay(Activity activity, final ZY_PayParams params, final IabHelper iabHelper) {
        if (UserModel.getInstance().getLogin_Token() == null) {
            ToastUtil.showToast(activity, "请先登录");
        } else {
            String url = "";

            String game_order_id = URLEncoder.encode(params.getGame_order_id());
            String game_other = URLEncoder.encode(params.getGame_other());
            final String goods_id = params.getGoods_id();
            String goods_name = URLEncoder.encode(params.getGoods_name());
            double goods_price = params.getGoods_price();
            String sandbox = params.getSandbox();
            int pay_num = params.getPay_num();

            String gid = ConstantValue.ZY_GAMEID + "";
            String cid = ConstantValue.ZY_CID + "";
            String sid = ConstantValue.ZY_SERVER_AUTHCODE;
            //            String ext = URLEncoder.encode(getExt(mContext));//ConstantValue.ZY_ext;
            String ext = ConstantValue.ZY_ext;
            String token = SharedPreferencesHelper.getInstance().getToken(mContext);
            String pay_money = pay_num * goods_price + "";
            String sign = "cid=" + cid + "&ext=" + ext + "&game_order_id=" + game_order_id + "&game_other=" + game_other + "&gid=" + gid + "&goods_id=" + goods_id
                    + "&goods_name=" + goods_name + "&goods_price=" + goods_price + "&pay_money=" + pay_money + "&pay_num=" + pay_num + "&sandbox=" + sandbox + "&sid=" + sid + "&token=" + token + ConstantValue.ZY_KEY;
            String sign_md5 = MD5Util.getMd5(sign);
            url = "cid=" + cid + "&gid=" + gid + "&sid=" + sid + "&ext=" + ext
                    + "&token=" + token + "&pay_money=" + pay_money
                    + "&game_order_id=" + game_order_id + "&game_other=" + game_other + "&sandbox=" + sandbox + "&goods_id=" + goods_id
                    + "&goods_name=" + goods_name + "&goods_price=" + goods_price + "&pay_num=" + pay_num + "&token=" + token + "&sign=" + sign_md5;

            switch (initResult.getPay_way()) {
                case 0 ://钱海支付
                    final Zy_Dialog_PayWay zyDialogPayWay = Zy_Dialog_PayWay.getInstance(mContext);
                    zyDialogPayWay.show();
                    final String finalUrl = url;
                    zyDialogPayWay.setIPayWaySelectListener(pay_money,new Zy_Dialog_PayWay.IPayWaySelectListener() {
                        @Override
                        public void onSelectedPayWay(int payWay) {
                            switch (payWay) {
                                case 0 :
                                    Intent intent = new Intent(mContext, ZY_Act_WebView.class);
                                    ZY_Toolbar main = new ZY_Toolbar(SharedPreferencesHelper.getInstance().getPayUrl(mContext), finalUrl, 1);
                                    LogHelper.i("sss", SharedPreferencesHelper.getInstance().getPayUrl(mContext) + "?" + finalUrl);
                                    intent.putExtra(ConstantValue.TOOLBARFLAG, main);
                                    mContext.startActivity(intent);
                                    break;
                                case 1 :
                                    googlePay(params, iabHelper);
                                    break;
                            }

                            zyDialogPayWay.dissDialog();
                        }
                    });

                    break;
                case 1://Google支付
                    googlePay(params, iabHelper);
                    break;
            }
        }
    }

    private void googlePay(final ZY_PayParams params, IabHelper iabHelper) {
        mIabHelper = iabHelper;
        //建立Google连接
        if(mIabHelper.isSetup){
            purchase(params);
            return;
        }
        mIabHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() {
            @Override
            public void onIabSetupFinished(IabResult result) {
                if (!result.isSuccess()) {
                    ToastUtil.showToast(mContext,result.getMessage());
                    return;
                }
                purchase(params);
            }
        });
    }


    /**
     *  购买商品
     * @param params 订单参数
     */
    private void purchase(final ZY_PayParams params) {
        try {
            String goods_id = params.getGoods_id();
            String goodsType = params.getGoods_type();

            //1.检查此商品是否已经购买并未消费
            Inventory inventory = new Inventory();
            int success = mIabHelper.queryPurchases(inventory, goodsType);
            if(success == 0){
                if(inventory.hasPurchase(goods_id)){//已经购买 请先去消费
                    Log.i("GD", "inventory.hasPurchase(goods_id) 已经购买此商品");
                    Purchase purchase = inventory.getPurchase(goods_id);
                    if(purchase != null){
                        if(goodsType.equals("subs")){
                            ToastUtil.showToast(mContext,"您已经订阅了此商品,不可重复订阅");
                        }else{
                            Log.i("GD", "inventory.hasPurchase(goods_id) 已经有此商品");
                            consumePurchase(purchase,params);
                        }
                    }
                    return;
                }
            }

            //2.去购买商品
            mIabHelper.launchPurchaseFlow(mContext, goods_id, 1, new IabHelper.OnIabPurchaseFinishedListener() {
                @Override
                public void onIabPurchaseFinished(IabResult result, Purchase info) {
                    if(result.isFailure()){
                        PayResult payResult = new PayResult();
                        payResult.setResultCode(CmCode.CODE_PAY_FAIL);
                        payResult.setExtension(result.getMessage());
                        onPayResult(payResult);
                    }else{
                        consumePurchase(info,params);
                    }
                }
            });
        } catch (IabHelper.IabAsyncInProgressException e) {
            e.printStackTrace();
        } catch (RemoteException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * Google支付成功马上消费
     * @param purchase 商品
     * @param params 订单参数
     */
    private void consumePurchase(Purchase purchase, final ZY_PayParams params) {
        try {
            mIabHelper.consumeAsync(purchase, new IabHelper.OnConsumeFinishedListener() {
                @Override
                public void onConsumeFinished(Purchase purchase, IabResult result) {
                    if(result.isFailure()){
                        PayResult payResult = new PayResult();
                        payResult.setResultCode(CmCode.CODE_PAY_FAIL);
                        payResult.setExtension(result.getMessage());
                        onPayResult(payResult);
                    }else{
                        //支付事件
                        AppEventsLogger logger = AppEventsLogger.newLogger(mContext, mContext.getResources().getString(R.string.GSDK_facebook_app_id));
                        logger.logPurchase(BigDecimal.valueOf(2000), Currency.getInstance("USD"));

                        HttpUtil.googlePay(purchase,params,mContext,consumeCallBack);
                    }
                }
            });
        } catch (IabHelper.IabAsyncInProgressException e) {
            e.printStackTrace();
        }
    }


    /**
     * 支付回调
     */
    NetHttpUtil.DataCallback consumeCallBack = new NetHttpUtil.DataCallback() {
        @Override
        public void callbackSuccess(Object paramObject) {
            PayResult payResult = new PayResult();
            payResult.setResultCode(CmCode.CODE_PAY_SUCCESS);
            onPayResult(payResult);
            Log.i("GD", paramObject.toString() + "Google支付成功");
        }

        @Override
        public void callbackError(String error) {
            PayResult payResult = new PayResult();
            payResult.setResultCode(CmCode.CODE_PAY_FAIL);
            payResult.setExtension(error);
            onPayResult(payResult);
            Log.i("GD", error + "Google支付失败");
        }
    };





    @Override
    public void submitServerData(final GameServerParams params) {
        this.mServerId = params.getServerId();
        getContext().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                String other = "";
                JSONObject json = new JSONObject();
                try {
                    json.put("role", params.getRoleLevel()); // 角色等级
                    json.put("rolename", params.getRoleName());
                    json.put("serviceName", params.getServerName());
                    other = json.toString();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                HttpUtil.submitServerData(getContext(), params.getServerId(), other, onSubCallback);
            }
        });
    }

    @Override
    public void changeUser() {
        logout();

        Zy_Dialog_main login = Zy_Dialog_main.getInstance(mContext);
        login.show();
    }

    @Override
    public void removeFloatButton() {
        if (FloatWindow.getInstance() == null) {
            return;
        }
        FloatWindow.getInstance().remove();

    }


    DataCallback<JSONObject> onSubCallback = new DataCallback<JSONObject>() {

        @Override
        public void callbackSuccess(JSONObject paramObject) {

        }

        @Override
        public void callbackError(String error) {

        }
    };

    @SuppressLint("NewApi")
    public String getServerId() {
        if (TextUtils.isEmpty(this.mServerId)) {
            return "";
        }
        return this.mServerId;
    }


    public void out() {
        HttpUtil.logout(mContext, outCallBack);
    }

    DataCallback<JSONObject> outCallBack = new DataCallback<JSONObject>() {

        @Override
        public void callbackSuccess(JSONObject paramObject) {
            LogHelper.i("注销接口", paramObject.toString());
            hideFloatButton();
            onLogout();
            if ("0".equals(paramObject.optString("code"))) {
                UserDao userDao = new UserDao();
                userDao.out();
            }
        }

        @Override
        public void callbackError(String error) {

        }
    };

    public void game_role() {
        //HttpUtil.game_server(mContext, gameCallBack);
    }

    DataCallback<JSONObject> gameCallBack = new DataCallback<JSONObject>() {
        @Override
        public void callbackSuccess(JSONObject paramObject) {
            LogHelper.i("game_role接口:", paramObject.toString());
        }

        @Override
        public void callbackError(String error) {
            LogHelper.i("game_role接口:", "失败");
        }
    };

    public void game_online_time() {
        String token = SharedPreferencesHelper.getInstance().getToken(mContext);
        String login_token = UserModel.getInstance().getLogin_Token();
        String gameJson = SharedPreferencesHelper.getInstance().getGameJson(mContext);
        HttpUtil.game_online_time(mContext, gameline, gameJson, login_token, token);
    }

    DataCallback<JSONObject> online_time = new DataCallback<JSONObject>() {
        @Override
        public void callbackSuccess(JSONObject paramObject) {
            LogHelper.i("game_role接口:", paramObject.toString());
        }

        @Override
        public void callbackError(String error) {
            LogHelper.i("game_role接口:", "失败");
        }
    };

    public void setContext(Activity context) {
        this.mContext = context;
    }

    public void register() {
        Zy_Dialog_main.getInstance(mContext).show();
    }


    public void gameRole(GameServerParams gameServerParams) {

      /* 测试
       gameServerParams.setRoleName("测试");
        gameServerParams.setServerName("测试");
        gameServerParams.setRoleLevel("88");
        gameServerParams.setServerId("125");*/
        HttpUtil.game_server(mContext, gameServerParams, gameCallBack);
    }

    public void stopSdk() {
        isInit = false;
        if (null != serviceIntent) {

            mContext.stopService(serviceIntent);
        }
        //        FloatWindow.getInstance().remove();
        //        FloatToolBar.getInstance().recycle();
        LogHelper.i("sss", "stop");
    }

    NetHttpUtil.DataCallback gameline = new NetHttpUtil.DataCallback() {
        @Override
        public void callbackSuccess(Object paramObject) {

            LogHelper.i("sss", paramObject.toString() + "在线");

        }

        @Override
        public void callbackError(String error) {
            LogHelper.i("sss", "在线失败");
        }
    };


}
